package ua.openmedis;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerUtils {
	
	private final static Logger log = LoggerFactory.getLogger(ServerUtils.class);
	
	private static EntityManagerFactory emf;
	
	public static EntityManager getEntityManager(){
		if (emf == null){
			//create emf
			log.debug("Initializing EntityManager");
			try{
				emf = Persistence.createEntityManagerFactory("openmedisDatasource");
				log.debug("EntityManagerFactory created");
			} catch(Exception ex){
				log.error("Error while creating EntityManagerFactory", ex);
			}
		}
		if(emf != null){
			return emf.createEntityManager();
		} else {
			log.warn("EntityManagerFactory was not created. Returning null EntityManager");
			return null;
		}
	}

}
